from urllib import request,parse
import random
import time
import hashlib
import json

def fanyi(content):
    try:
        url = 'http://fanyi.youdao.com/translate?smartresult=dict&smartresult=rule'
        data = {}
        n = content
        S = "fanyideskweb"
        D = "ebSeFb%=XZ%T[KZ)c(sy!"
        r = str(int(time.time()*1000) + random.randint(1,10))
        o = hashlib.md5((S+n+r+D).encode('utf-8')).hexdigest()
        data['i'] = content
        data['from'] = "AUTO"
        data['to'] = "AUTO"
        data['smartresult'] = "dict"
        data['client'] = S
        data['salt'] = r
        data['sign'] = o
        data['doctype'] = 'json'
        data['version'] = '2.1'
        data['keyfrom'] = 'fanyi.web'
        data['action'] = 'FY_BY_REALTIME'
        data['typeoResult'] = 'false'

        data = parse.urlencode(data)
		#设置cookies
        newTime = int(time.time()*1000)
        cookie = 'OUTFOX_SEARCH_USER_ID_NCOO=975267269.2276318; OUTFOX_SEARCH_USER_ID=-507607894@10.169.0.83; fanyi-ad-id=44881; fanyi-ad-closed=1; JSESSIONID=aaa_f-2Ns9xPN5yvN4nqw; ___rl__test__cookies='+str(newTime)
        headers = {'Content-Length':len(data),"Cookie":cookie}
        req = request.Request(url,data=bytes(data,encoding='utf-8'),headers=headers)
        res = request.urlopen(req)
        str_json = res.read().decode('utf-8','ignore')
        myjson = json.loads(str_json)
        result = myjson['translateResult'][0][0]['tgt']
        print("输入的内容被翻译为："+result)
    except Exception as err:
        print(err)




if __name__ == '__main__':
    while True:
        content = input('请输入需要翻译的内容：')
        if content == 'q':
            break
        fanyi(content)


